package com.xyz.jira.plugin;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.bc.issue.IssueService;
import com.atlassian.jira.issue.AttachmentManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.web.util.AttachmentException;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.core.entity.GenericEntityException;

/**
 * A resource of message.
 */
@Path("/anonIssueAttachment")
public class AnonIssueAttachment {

	@POST
	@AnonymousAllowed
	@Produces({ MediaType.TEXT_HTML })
	public String addAttachment(@Context HttpServletRequest request) {
		
		String iid = request.getParameter("iid");
		String ikey = request.getParameter("ikey");
		System.out.println(iid + " : " + ikey);
		String fileRepository = "C:\\Temp\\";
		if (ServletFileUpload.isMultipartContent(request)) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			
			Iterator<FileItem> iter = items.iterator();
			if (items != null) {
				iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					if (!item.isFormField() && item.getSize() > 0) {
						String fileName = processFileName(item.getName());
						try {
							File file = new File(fileRepository + fileName);
							item.write(file);
							IssueService iService = ComponentManager.getInstance().getIssueService();
							MutableIssue issue;
							if ( iid != null && iid.length() > 0 ) {
								issue = iService.getIssue(null, new Long(iid)).getIssue();
							} else if ( ikey != null && ikey.length() > 0 ) {
								issue = iService.getIssue(null, ikey).getIssue();
							} else {
								return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No issue id/key provided</html>";
							}
							AttachmentManager attachmentManager = ComponentManager
									.getInstance().getAttachmentManager();
							try {
								ChangeItemBean changeItemBean = attachmentManager
										.createAttachment(file, fileName,
												item.getContentType(), null,
												issue.getGenericValue());
								return "<html><head></head><body onload=\"parent.uploadDone()\">OK</html>";
							} catch (GenericEntityException gee) {
								System.err.println(gee);
								return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: GEE</html>";
							} catch (AttachmentException aee) {
								System.err.println(aee);
								return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: AEE</html>";
							}
						} catch (Exception e) {
							e.printStackTrace();
							return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR</html>";
						}
					}
				}
				return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No file item found</html>";
			} else {
				return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No upload item found</html>";
			}
		} else {
			return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: Not a multipart form</html>";
		}
	}

	private String processFileName(String fileNameInput) {
		String fileNameOutput = null;
		fileNameOutput = fileNameInput.substring(
				fileNameInput.lastIndexOf("\\") + 1, fileNameInput.length());
		return fileNameOutput;
	}
}